﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Chapter16.Code01.KarliCards_GUI
{
    using KarliCards_GUI.ViewModel;
    using System.IO;
    using System.Xml.Serialization;

    /// <summary>
    /// StartGame.xaml 的交互逻辑
    /// </summary>
    public partial class StartGame : Window
    {
        private GameOptions gameOptions;

        public StartGame()
        {
            InitializeComponent();
            DataContextChanged += StartGame_DataContextChanged;
        }

        private void StartGame_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            gameOptions = DataContext as GameOptions;
            ChangeListBoxOptions();
        }

        private void ChangeListBoxOptions()
        {
            if (gameOptions.PlayAgainstComputer)
                playerNameListBox.SelectionMode = SelectionMode.Single;
            else
                playerNameListBox.SelectionMode = SelectionMode.Multiple;
        }

        private void playerNameListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (gameOptions.PlayAgainstComputer)
            {
                okButton.IsEnabled = (playerNameListBox.SelectedItems.Count == 1);
            }
            else
            {
                okButton.IsEnabled = (playerNameListBox.SelectedItems.Count == gameOptions.NumberOfPlayers);
            }
        }

        private void addNewPlayerButton_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(newPlayerTextBox.Text))
            {
                gameOptions.AddPlayer(newPlayerTextBox.Text);
                newPlayerTextBox.Text = string.Empty;
            }
        }

        private void okButton_Click(object sender, RoutedEventArgs e)
        {
            var gameOptions = DataContext as GameOptions;
            gameOptions.SelectedPlayers = new List<string>();
            foreach (string item in playerNameListBox.SelectedItems)
            {
                gameOptions.SelectedPlayers.Add(item);
            }
            DialogResult = true;
            Close();
        }
    }
}
